<?php

namespace App\Http\Controllers\Admin\V1;

use Exception;
use App\Models\Section;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\SectionRequest;
use App\Transformers\Admin\SectionUserTransformer;
use Illuminate\Support\Facades\Redis;

class SectionController extends Controller
{
    // 获取最大部门等级限制
    public $section_level = Section::SECTION_LEVEL;

    /**
     * 显示部门列表
     *
     * @param Request $request
     * @return Response
     */
    public function index(Request $request)
    {
        // 实现name字段模糊搜索
        if ($request->has('name')) {
            $data = Section::query()->select('id', 'name', 'pid', 'level', 'status')
                ->pimp()
                ->get()
                ->toArray();
        } else {
            $data = getCacheSection();

            $data = makeTree($data);
        }
        return $this->response->array(['data' => $data]);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param SectionRequest $request
     * @return Response
     */
    public function store(SectionRequest $request)
    {
        $data = $request->input();

        $data['level'] = 1;

        // 对pid进行验证

        if (($data['pid'] != 0)) {

            $pSection = Section::query()->where('id', $data['pid'])->first() ?? '';

            if (empty($pSection)) {
                return $this->response->error('pid不存在', 422);
            }

            // 新部门的level等级
            $data['level'] = $pSection['level'] += 1;

            // 判断新部门等级是否超出限制
            if ($data['level'] > Section::SECTION_LEVEL) {
                return $this->response->error('部门最多' . $this->section_level . '级', 422);
            }
        }

        Section::create($data);

        Redis::del('CacheSection');

        return $this->response->created();
    }

    /**
     * Display the specified resource.
     *
     * @param int $id
     * @return Response
     */
    public function show(int $id)
    {
        // 获取当前部门数据
        $this_data = Section::query()
            ->where('id', $id)
            ->select('id', 'name', 'pid', 'status')
            ->firstOrFail();

        // 获取所有部门数据
        $data = Section::query()->select('id', 'name', 'pid', 'level')
            ->get()
            ->toArray();

        $tree = makeTree($data);

        return $this->response->array(['thisSection' => $this_data, 'allSections' => $tree]);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param SectionRequest $request
     * @param Section $section
     * @return Response
     */
    public function update(SectionRequest $request, Section $section)
    {
        $data = $request->input();

        // 对pid进行验证
        if (!empty($data['pid'])) {

            // 查询是否有子级部门
            $children = Section::query()->where('pid', $section['id'])->first() ?? '';

            if (!empty($children)) {
                return $this->response->error('不允许修改含有子级部门的部门', 422);
            }

            if (($data['pid'] != 0)) {

                $pSection = Section::query()->where('id', $data['pid'])->first() ?? '';

                if (empty($pSection)) {
                    return $this->response->error('pid不存在', 422);
                }

                // 新部门的level等级
                $data['level'] = $pSection['level'] += 1;

                // 判断新部门等级是否超出限制
                if ($data['level'] > Section::SECTION_LEVEL) {
                    return $this->response->error('部门最多' . $this->section_level . '级', 422);
                }

            }
        }

        // 更新部门数据
        $section->update($data);

        Redis::del('CacheSection');

        return $this->response->noContent();
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param Section $section
     * @return Response
     */
    public function destroy(Section $section)
    {
        // 获取所有部门
        $arr = Section::all()->toArray();

        $res = getMenuTree($arr, $section->id, $section->level);

        // 需要删除的id数组
        $ids = [];
        foreach ($res as $item) {
            array_push($ids, $item['id']);
        }

        // 导入当前id到需要删除的id数组
        array_push($ids, $section->id);

        try {
            DB::beginTransaction();

            // 删除自己以及所有子级
            Section::query()
                ->whereIn('id', $ids)
                ->delete();

            // 删除与用户的关联数据
            DB::table('user_has_section')
                ->whereIn('section_id', $ids)
                ->delete();

            DB::commit();

            Redis::del('CacheSection');

            return $this->response->noContent();
        } catch (Exception $e) {
            DB::rollBack();
            report($e);
            return $this->response->errorBadRequest('参数错误');
        }
    }

    /**
     * @param Section $section
     * @return \Dingo\Api\Http\Response
     */
    public function status(Section $section)
    {
        // 获取到状态的值 取反
        $section->status = !$section->status;

        $section->save();

        Redis::del('CacheSection');

        return $this->response->noContent();
    }

    /**
     * 获取该部门下面的人员
     * @param Section $section
     * @return \Dingo\Api\Http\Response
     */
    public function getList(Section $section)
    {
        $data = $section->users()->paginate($this->pageLimit());

        return $this->response->paginator($data, new SectionUserTransformer());
    }
}
